﻿using System;
using System.Web.Mvc;
using MemcachedProviders.Cache;
using sBlog.Net.Common;
using sBlog.Net.CustomExceptions;
using sBlog.Net.Domain.Entities;
using sBlog.Net.Domain.Interfaces;
using sBlog.Net.Models;

namespace sBlog.Net.Controllers
{
    public class ViewController : Controller
    {
        [Authorize]
        public ActionResult View(string year, string month, string url, string status)
        {
            var currentPost = MemcaheService.GetPostByUrl(url, 1);
            if (currentPost == null)
            {
                throw new UrlNotFoundException("Unable to find a post w/ the url {0} for the month {1} and year {2}", url, month, year);
            }

            ViewPostOrPageModel model = ProcessViewPostOrPageModel(currentPost);

            return View(model);
        }

        private ViewPostOrPageModel ProcessViewPostOrPageModel(PostEntity currentPost)
        {
            ViewPostOrPageModel model = new ViewPostOrPageModel();
            model = model = new ViewPostOrPageModel
            {
                Post = currentPost,
                BlogSharingEnabled = true,
                SharingType = 3,
                UserCanEdit = Request.IsAuthenticated && (currentPost.OwnerUserID == GetUserId() || User.IsInRole("SuperAdmin")),
                BlogName = "Mlog",
                BlogCaption = "Mlog!",
                DisqusEnabled = false,
                DisqusUrl = GetRootUrl().TrimEnd('/') + Url.RouteUrl("IndividualPost", new { year = currentPost.PostAddedDate.Year.ToString(), month = currentPost.PostMonth, url = currentPost.PostUrl }),
                ShortName = "",
                DisqusDevMode = true
            };
            return model;
        }

        protected int GetUserId()
        {
            var userId = -1;
            if (Request.IsAuthenticated)
            {
                var userIdentity = (IUserInfo)User.Identity;
                userId = Int32.Parse(userIdentity.UserId);
            }
            return userId;
        }

        protected string GetRootUrl()
        {
            return string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
        }
    }
}
